"""
处理通过WIFI连接到控制端的ESP设备
"""

from typing import List
from flask import Blueprint, request
import json

from shared_types import DeviceFunctionalConfig
from ..services import DevicesManager

blueprint_devices = Blueprint("devices", __name__, url_prefix="/api/devices")


@blueprint_devices.route("/all", methods=["GET"])
def all_devices():
    from ..app import devices_manager
    return (
        json.dumps([item.to_dict()
                   for item in devices_manager.get_all_devices()]),
        200,
    )


@blueprint_devices.route("/all-configs", methods=["GET"])
def all_devices_configs():
    # print(DevicesManager.get_instance().dev_cfg_mgr.devices_configs)
    return (
        json.dumps(
            [item for item in DevicesManager.get_instance().dev_cfg_mgr.devices_configs]),
        200,
    )


@blueprint_devices.route("/save-configs", methods=["POST"])
def save_devices_configs():
    config_data: List[DeviceFunctionalConfig] = json.loads(request.data)
    # 检查config_data中，同样name的字段是否有多个activated为True。
    activated_count = {item["device_name"]: 0 for item in config_data}
    for item in config_data:
        if item["activated"]:
            activated_count[item["device_name"]] += 1
            if activated_count[item["device_name"]] > 1:
                return (
                    f"Duplicate device name: {item['device_name']}",
                    400,
                )
    dev_cfg_mgr = DevicesManager.get_instance().dev_cfg_mgr
    dev_cfg_mgr.devices_configs = config_data
    dev_cfg_mgr.save_configs()
    return (
       "Saving device functional configs succeeded.",
        200,
    )
